package net.wanho.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.wanho.shop.dto.AliPayDTO;
import net.wanho.shop.properties.AlipayProperties;
import net.wanho.shop.service.OrderService;
import net.wanho.shop.vo.AjaxResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Api("14.支付功能接口")
@CrossOrigin
@Slf4j
public class AlipayController {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradePagePayRequest payRequest;

    @Resource
    private AlipayProperties alipayProperties;
    @Resource
    private OrderService orderService;

    /**
     * 支付方法
     */
    @SneakyThrows
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody AliPayDTO aliPayDTO) {
        // 封装业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", aliPayDTO.getOrderNo()); // 订单号
        bizContent.put("subject", aliPayDTO.getSubject()); //  订单名称
        bizContent.put("total_amount", aliPayDTO.getTotalAmount()); // 订单总金额
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 产品码，固定值
        bizContent.put("timeout_express", "15m"); // 超时时间，15分钟
        payRequest.setBizContent(bizContent.toString());

        // 向支付宝发起支付请求
        String result = alipayClient.pageExecute(payRequest).getBody();
//        // 将结果返回给前端，进入支付宝用户登录页面
//        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().println(result);
        orderService.updateOrderStatus(aliPayDTO.getOrderNo());
        return AjaxResult.success("ok", result);
    }

    /**
     * 异步通知
     */
    @PostMapping("/notify")
    public String notify(@RequestParam Map<String, String> params) throws AlipayApiException {
        System.out.println(params);
        /**
         * 进行验签操作，防止签名被篡改
         */
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if (!flag) {
            log.info("验证签名失败！");
            return "fail";
        }

        /**
         * 判断返回的订单号、订单总金额等是否与发送的一致，防止数据被篡改
         */
        String out_trade_no = params.get("out_trade_no");
        String total_amount = params.get("total_amount");

        /**
         * 判断支付宝返回的状态是否正常
         */
        String trade_status = params.get("trade_status");
        if (!trade_status.equals("TRADE_SUCCESS")) {
            log.info("交易失败！");
            return "fail";
        }

        /**
         * 更新相应的订单状态，例如将订单标记为已支付、更新库存等
         */

        System.out.println("---------------------订单已支付，修改本地数据库");

        return "success";
    }
}